from fastapi import APIRouter, HTTPException
# 在 user_api.py 文件中
from fastApi.database.base import get_db
from pydantic import BaseModel

router = APIRouter()

# 请求模型
class LoginRequest(BaseModel):
    username: str
    password: str


class RegisterRequest(BaseModel):
    username: str
    email: str
    password: str
    is_admin: int = 0  # 默认为普通用户


# 用户登录  安全性：POST 更安全，不会在 URL 中暴露敏感信息
@router.post("/auth/login")
def login(request: LoginRequest):
    conn = get_db()
    result = conn.selectData(
        "SELECT * FROM users WHERE username = ? AND password = ?",
        [request.username, request.password]
    )
    if not result:
        raise HTTPException(status_code=400, detail="用户名或密码错误")
    return {
        "id": result[0]["id"],
        "username": result[0]["username"],
        "email": result[0]["email"],
        "is_admin": result[0]["is_admin"]
    }

@router.post("/auth/register")
def register(request: RegisterRequest):
    conn = get_db()
    result = conn.selectData("SELECT * FROM users WHERE username = ?", [request.username])
    if result:
        raise HTTPException(status_code=400, detail="用户名已存在")
    success = conn.operation_sql(
        "INSERT INTO users (username, email, password, is_admin) VALUES (?, ?, ?, ?)",
        [request.username, request.email, request.password, request.is_admin]
    )
    if not success:
        raise HTTPException(status_code=500, detail="注册失败")
    return {"code": 200, "msg": "注册成功", "username": request.username, "email": request.email}